﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text.RegularExpressions;
public partial class Manage_Emp2_Fact2Detail : AdminPageBase
{
    int id;
    int issure;
	private string returnURL;
    protected void Page_Load(object sender, EventArgs e)
    {
        CheckAdmin();
        GetUserPermisions();
        GetClassRecordId();
		returnURL = Request.QueryString["returnURL"].ToString();
        if (!IsPostBack)
        {

            // 正确的属性设置方法
            this.GridView1.Attributes.Add("SortExpression", "RecordId");
            this.GridView1.Attributes.Add("SortDirection", "ASC");
           
            BindRecord();
        }
    }
     
    protected void GetClassRecordId()
    {
        if (Request.QueryString["id"] == null)
        {
            id = 0;

        }
        else
        {
            id = Convert.ToInt32(Request.QueryString["id"]);

        }
        if (Request.QueryString["Num"] == null)
        {
            lblNum.Text = "";
        }
        else
            lblNum.Text = Request.QueryString["Num"].ToString();
        if (Request.QueryString["Title"] == null)
            txttitle.Text = "";
        else
            txttitle.Text = Request.QueryString["Title"].ToString();
        if (Request.QueryString["IsSure"]!=null)
        {
            issure = Convert.ToInt32(Request.QueryString["IsSure"].ToString());
            hdfconfirm.Value = Request.QueryString["IsSure"].ToString();
        }
        if (issure == 0)
            btnconfirm.Visible = true;
        else
            btnconfirm.Visible = false;
    }
    protected void BindRecord()
    {

        if (id != 0)
        {
            DataSet dsemp = jtDataAccess.GetGetRecordByClassRecordId(id);
            if (CoreTools.CheckDataSet(dsemp))
            {
                // 获取GridView排序数据列及排序方向
                string sortExpression = this.GridView1.Attributes["SortExpression"];
                string sortDirection = this.GridView1.Attributes["SortDirection"];

                // 根据GridView排序数据列及排序方向设置显示的默认数据视图
                if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                {
                    dsemp.Tables[0].DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                }

                // GridView绑定并显示数据
                GridviewControl.GridViewDataBind(this.GridView1, dsemp.Tables[0]);


            }
            else
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("RecordId");
                dt.Columns.Add("CenterName");
                dt.Columns.Add("CenterId");
                dt.Columns.Add("CustomerCode");
                dt.Columns.Add("CustomerId");
                dt.Columns.Add("CustomerName");
                dt.Columns.Add("ClassTypeName");
                dt.Columns.Add("ClassCode");
                dt.Columns.Add("ClassId");
                dt.Columns.Add("ClassName");
                dt.Columns.Add("TeacherName");
                dt.Columns.Add("Time");
                dt.Columns.Add("FactTimes");
                dt.Columns.Add("OpenTime");
                dt.Columns.Add("PlanTimes");
                dt.Columns.Add("GradeId");
                dt.Columns.Add("GradeName");
                dt.Columns.Add("");
                GridviewControl.GridViewDataBind(this.GridView1, dt);
                btnconfirm.Visible = false;

            }
        }
        else
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("RecordId");
            dt.Columns.Add("CenterName");
            dt.Columns.Add("CenterId");
            dt.Columns.Add("CustomerCode");
            dt.Columns.Add("CustomerId");
            dt.Columns.Add("CustomerName");
            dt.Columns.Add("ClassTypeName");
            dt.Columns.Add("ClassCode");
            dt.Columns.Add("ClassId");
            dt.Columns.Add("ClassName");
            dt.Columns.Add("TeacherName");
            dt.Columns.Add("Time");
            dt.Columns.Add("FactTimes");
            dt.Columns.Add("OpenTime");
            dt.Columns.Add("PlanTimes");
            dt.Columns.Add("GradeId");
            dt.Columns.Add("GradeName");
            dt.Columns.Add("");
            GridviewControl.GridViewDataBind(this.GridView1, dt);
            GridviewControl.ResetGridView(this.GridView1);
            btnconfirm.Visible = false;

        }
    }
    protected void CheckAdmin()
    {
        if (AdminSessionHelper.UserDetails == null)
        {
            JsHelper.TopAlertRedirect("请先登录", "../login.aspx", this.Page);
        }


    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindRecord();
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //首先判断是否是数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //当鼠标停留时更改背景色
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FCFDEE'");
            //当鼠标移开时还原背景色
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
           // LinkButton BtnDelete = (LinkButton)e.Row.Cells[10].Controls[2];
           // if (BtnDelete.Text == "删除")
          // {
         //       ((LinkButton)e.Row.Cells[10].Controls[2]).Attributes.Add("onclick", "javascript:return confirm('您确定要删除该记录吗？')");
         //  }
           
        }
        if (edit == 1)
            ((CommandField)GridView1.Columns[12]).ShowEditButton = true;
        else
            ((CommandField)GridView1.Columns[12]).ShowEditButton = false;
        if (delete == 1)
            ((CommandField)GridView1.Columns[12]).ShowDeleteButton = true;
        else
            ((CommandField)GridView1.Columns[12]).ShowDeleteButton = false;
        if (hdfconfirm.Value.Equals("1"))
        {
            ((CommandField)GridView1.Columns[12]).ShowEditButton = false;
            ((CommandField)GridView1.Columns[12]).ShowDeleteButton = false;
        }
       

    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        UserType ut = new UserType();//用户自定义类型
        DataTable RecordTable = ut.GetRecordTableType();

        DataRow RecordTableRow;
        int RecordId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString());


        RecordTableRow = RecordTable.NewRow();
        RecordTableRow["RecordId"] = RecordId;
        RecordTable.Rows.Add(RecordTableRow);

        RecordTable.AcceptChanges();
        int flag = jtDataAccess.OpRecord(JTDataAccess.OpType.Delete, RecordTable);
        switch (flag)
        {
            case 0:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除失败！"), false);
                break;

            case 1:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("删除成功！"), false);
                break;
            default:
                break;
        }

        GridView1.EditIndex = -1;
        BindRecord();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
       
        BindRecord();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int flag = 0;
        int RecordId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0].ToString());
        int classid = Convert.ToInt32(((HiddenField)GridView1.Rows[e.RowIndex].FindControl("hdfClassId")).Value);
        int centerId = Convert.ToInt32(((HiddenField)GridView1.Rows[e.RowIndex].FindControl("hdfcenterId")).Value);
        int gradeId = Convert.ToInt32(((HiddenField)GridView1.Rows[e.RowIndex].FindControl("hdfGradeId")).Value);
        int plantimes = Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].FindControl("lblPlanTimes")).Text.ToString());
        decimal time = Convert.ToDecimal(((Label)GridView1.Rows[e.RowIndex].FindControl("lblTime")).Text.ToString());
        HiddenField hdfc = (HiddenField)GridView1.Rows[e.RowIndex].FindControl("hdfCustomerId");
        string dd = hdfc.Value;
        int customerId = Convert.ToInt32(((HiddenField)GridView1.Rows[e.RowIndex].FindControl("hdfCustomerId")).Value);
        int FactTimes = 0;
        string TeacherName = "";
        string opentime = "";
        TextBox cFactTimes = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtFactTimes");
        TextBox cTeacherName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtTeacherName");
        TextBox copentime = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtOpenTime");
        if (cFactTimes.Text == "")
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("请填写实际培训人次！"), false);
            cFactTimes.Focus();
        }
        else if (!Regex.IsMatch(cFactTimes.Text.ToString(), "^[1-9]*[1-9][0-9]*$"))
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("实际培训人次必须为正整数！"), false);
            cFactTimes.Focus();
        }
        else
            FactTimes = Convert.ToInt32(cFactTimes.Text.Trim());
        if (cTeacherName.Text == "")
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("请填写导师姓名！"), false);
            cTeacherName.Focus();
        }
        else if (!CoreTools.ProcessSqlStr(TeacherName, 0))
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert(ConfigHelper.ProcessSqlStrErroMsg), false);
        }
        else
            TeacherName = cTeacherName.Text.Trim();
        if (copentime.Text == "")
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("请填写开课时间！"), false);
            copentime.Focus();
        }
        else if (!Regex.IsMatch(copentime.Text.ToString(), "^([2-9]\\d{3})(0[1-9]|1[0-2])$"))
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("开课时间格式不正确,正确格式形如：201206！"), false);
            copentime.Focus();
        }
        else
            opentime = copentime.Text.Trim();
      

        if (FactTimes != 0&&TeacherName!=""&&opentime!="")
        {
            UserType ut = new UserType();//用户自定义类型
            DataTable RecordTable = ut.GetRecordTableType();
            DataRow RecordTableRow;
            RecordTableRow = RecordTable.NewRow();
            RecordTableRow["RecordId"] = RecordId;
            RecordTableRow["ClassRecordId"] = id;
            RecordTableRow["EmpTypeId"] = 2;
            RecordTableRow["ClassId"] = classid;
            RecordTableRow["Time"] = time;
            RecordTableRow["FactTimes"] = FactTimes;
            RecordTableRow["CenterId"] = centerId;
            RecordTableRow["CustomerId"] = customerId;
            RecordTableRow["CustomerId"] = customerId;
            RecordTableRow["TeacherName"] = TeacherName;
            RecordTableRow["OpenTime"] = opentime;
            RecordTableRow["PlanTimes"] = plantimes;
            RecordTableRow["GradeId"] = gradeId;
            RecordTable.Rows.Add(RecordTableRow);
            flag = jtDataAccess.OpRecord(JTDataAccess.OpType.Update, RecordTable);
            switch (flag)
            {
                case 1:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("操作成功！"), false);
                    break;
                case 0:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("操作失败，请重试！"), false);
                    break;
                default:
                    ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("操作成功！"), false);

                    break;
            }
            GridView1.EditIndex = -1;
            BindRecord();
        }
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        // 从事件参数获取排序数据列
        string sortExpression = e.SortExpression.ToString();

        // 假定为排序方向为“顺序”
        string sortDirection = "ASC";

        // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
        if (sortExpression == this.GridView1.Attributes["SortExpression"])
        {
            //获得下一次的排序状态
            sortDirection = (this.GridView1.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
        }

        // 重新设定GridView排序数据列及排序方向
        this.GridView1.Attributes["SortExpression"] = sortExpression;
        this.GridView1.Attributes["SortDirection"] = sortDirection;

        this.BindRecord();
    }
    protected void btnconfirm_Click(object sender, EventArgs e)
    {
        int flag = 0;
        if (GridView1.EditIndex != -1)
            flag = 1;
        else
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                Label lblTeacherName = (Label)GridView1.Rows[i].FindControl("lblTeacherName");
                Label lblFactTimes = (Label)GridView1.Rows[i].FindControl("lblFactTimes");
                Label lblOpenTime = (Label)GridView1.Rows[i].FindControl("lblOpenTime");
                if (lblFactTimes.Text == "" || lblOpenTime.Text == "" || lblTeacherName.Text == "")
                {
                    flag = 1;
                    break;
                }
            }
        }
        if (flag == 1)
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("请将列表中的项：导师姓名、实际培训人次、开课时间填写完整，且列表不处于编辑状态，再确认！"), false);
        }
        else
        {
            int f = 0;
            hdfconfirm.Value = "1";
            f=SaveClassRecord();
            if (f > 0)
            {
                BindRecord();
                btnconfirm.Enabled = false;
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("操作成功！"), false); 
           }
           
        }
    }
    protected void btnreturn_Click(object sender, EventArgs e)
    {
       // Response.Redirect("Fact2.aspx?MenuId="+MenuId);
		Response.Redirect(returnURL);
    }
    protected void btnsave_Click(object sender, EventArgs e)
    {
        int flag = SaveClassRecord();
        switch (flag)
        {
            case -1:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("操作失败，已经存在相同编号的课程！"), false);
                break;
            case 0:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("操作失败！"), false);
                break;
            default:
                ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert("操作成功！"), false);
                break;
        }
        GridviewControl.ResetGridView(this.GridView1);
    }
    protected int SaveClassRecord()
    {
        int flag = 0;
        string Num = lblNum.Text;
        int issure=Convert.ToInt32(hdfconfirm.Value);
        string title = txttitle.Text.Trim();
        if (!CoreTools.ProcessSqlStr(title, 0))
        {
            ScriptManager.RegisterStartupScript(up1, this.GetType(), "alert", CoreTools.JsAlert(ConfigHelper.ProcessSqlStrErroMsg), false);
            txttitle.Focus();
        }
        else
        {
            flag = jtDataAccess.OpClassRecord(JTDataAccess.OpType.Update, id, 2, Num, title, int.Parse(AdminSessionHelper.UserDetails["UserId"].ToString()), issure);

        }
        return flag;

    }
}